// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package actions

import (
	"encoding/base64"
	"gitee.com/orivil/morgine/xx"
	"gitee.com/tugoer/psy-testing/code/env"
	"io/ioutil"
	"net/http"
	"os"
)

func ServeImage(c *xx.Condition) {
	doc := xx.Doc{
		Name: "图片服务",
		Params: xx.Params{
			{
				In:     xx.Path,
				Schema: &serveImageParams{},
			},
		},
	}
	err := os.MkdirAll(env.Env.ImgDir, os.ModePerm)
	if err != nil {
		panic(err)
	}
	c.Doc(doc).GET().HandleFunc("/proxy-images/{file}.{ext}", func(ctx *xx.Context) {
		p := &serveImageParams{}
		if ctx.Unmarshal(p) {
			// 读取本地图片
			file := env.Env.ImageFile(p.File, p.Ext)
			_, err := os.Stat(file)
			if err != nil {
				if os.IsNotExist(err) {
					// 解析远程图片地址
					data, err := base64.RawURLEncoding.DecodeString(p.File)
					if err != nil {
						ctx.Error(err)
						return
					}
					URL := env.Env.ImageUrl(string(data) + "." + p.Ext)
					resp, err := http.Get(URL)
					if err != nil {
						ctx.Error(err)
						return
					}
					defer resp.Body.Close()
					data, err = ioutil.ReadAll(resp.Body)
					if err != nil {
						ctx.Error(err)
						return
					}
					// 保存远程图片到本地
					err = ioutil.WriteFile(file, data, os.ModePerm)
					if err != nil {
						ctx.Error(err)
						return
					}
				} else {
					ctx.Error(err)
					return
				}
			}
			// 服务本地图片
			http.ServeFile(ctx.Writer, ctx.Request, file)
		}
	})
}

type serveImageParams struct {
	File string `param:"file" desc:"需通过 base64 加密, 且删除最后的空白符(即后面的所有'='号)"`
	Ext  string `param:"ext"`
}
